package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

public class PullActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    String TAG=PullActivity.class.getName();
    private static final int MSG_RefreshData=101;
    private static final int MSG_MAIN=9001;
    private static final int MSG_COLORLIST=9002;
    private static final int MSG_PULLLIST=9003;
    private static final int MSG_PROCRESULT=9004;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID,BoardNo="";
    String ProduceMasterID="",ProduceCutMaID ="",MarkDeID="",MakeState="";
    //界面控件
    ListView colorList, pullList;
    Button btn_Refresh,btn_Close, btn_Delete,btn_Edit,btn_Submit;
    TextView text_pull_department,text_pull_operator,text_pull_formno,text_pull_formdate,text_pull_orderno,text_pull_styleno,text_pull_bedno, text_pull_markno;
    TextView text_pullhead_size1,text_pullhead_size2,text_pullhead_size3,text_pullhead_size4,text_pullhead_size5,text_pullhead_size6,text_pullhead_size7,text_pullhead_size8,
            text_pullhead_size9,text_pullhead_size10,text_pullhead_size11,text_pullhead_size12;
    TextView edit_pullvalue_paperName,edit_pullvalue_markWidth,edit_pullvalue_markLen,edit_pullvalue_useRate,edit_pullvalue_markOperator;
    TextView text_pullvalue_size1,text_pullvalue_size2,text_pullvalue_size3,text_pullvalue_size4,text_pullvalue_size5,text_pullvalue_size6,
            text_pullvalue_size7,text_pullvalue_size8,text_pullvalue_size9,text_pullvalue_size10,text_pullvalue_size11,text_pullvalue_size12,text_pullvalue_total;
    //用于与主Activity通讯;
    private Handler mainHandler;
    private JSONArray titleJson, colorJson,pullJson,procRstJSON;//用于存储WebService返回的结果;
    public static final String DB_Name ="bdmes.db";
    SQLiteDatabase mainDB;
    String curLevelNo, curProduceCutDeID,curProduceDetailID,curColor,curColorNo,curPertain;
    //媒体播放文件
    private static MediaPlayer mediaPlayer;
    int curPullListPosition=-1;
    Toast curToast;
    private ProgressDialog waitDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pull);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNo");
        curDepart=paramBundle.getString("CurDepart");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        CPUID=paramBundle.getString("CPUID");
        ProduceCutMaID =paramBundle.getString("ProduceCutMaID");
        MarkDeID=paramBundle.getString("MarkDeID");
        MakeState=paramBundle.getString("MakeState");
        System.out.println(paramBundle);
        InitView();
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        CreateDBTable();
        //消息调用刷新数据;
        Message msg=new Message();
        msg.what=MSG_RefreshData;
        handler.removeMessages(MSG_RefreshData);
        handler.sendMessage(msg);
        try {
            titleJson=new JSONArray("[]");
            colorJson=new JSONArray("[]");
            pullJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //创建数据库表
    private void CreateDBTable(){
        if (mainDB!=null) {
            //建表语句;
            mainDB.execSQL("Drop TABLE IF EXISTS PullCloth");
            //员工表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS PullCloth (ID INTEGER PRIMARY KEY AUTOINCREMENT,LevelNo int,ProduceCutDeID VARCHAR,ProduceDetailID VARCHAR,ProduceCutMaID VARCHAR,ColorNo VARCHAR, Color VARCHAR," +
                    "Pertain VARCHAR,BowlNo VARCHAR,IdentLen NUMERIC(8,2),LevelNum Int,PrepNum NUMERIC(8,2),RollNum NUMERIC(8,2),ShortLen NUMERIC(8,2),OwenLen NUMERIC(8,2))");
        }
    }
    //初始化界面
    private void InitView(){
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
        //提示框pd=new ProgressDialog(this);
        waitDialog= new ProgressDialog(this);
        waitDialog.setTitle(getString(R.string.SystemHint));
        //界面控件
        colorList=findViewById(R.id.colorList);
        colorList.setOnItemClickListener(this);
        pullList =findViewById(R.id.pullList);
        pullList.setOnItemClickListener(this);
        btn_Refresh=findViewById(R.id.btn_Refresh);
        btn_Refresh.setOnClickListener(this);
        btn_Close=findViewById(R.id.btn_Close);
        btn_Close.setOnClickListener(this);
        btn_Delete =findViewById(R.id.btn_Delete);
        btn_Delete.setOnClickListener(this);
        btn_Edit=findViewById(R.id.btn_Edit);
        btn_Edit.setOnClickListener(this);
        btn_Submit=findViewById(R.id.btn_Submit);
        btn_Submit.setOnClickListener(this);
        //各个标签;
        text_pull_department =findViewById(R.id.text_pull_department);
        text_pull_operator=findViewById(R.id.text_pull_operator);
        text_pull_formno=findViewById(R.id.text_pull_formno);
        text_pull_formdate=findViewById(R.id.text_pull_formdate);
        text_pull_orderno=findViewById(R.id.text_pull_orderno);
        text_pull_styleno=findViewById(R.id.text_pull_styleno);
        text_pull_bedno=findViewById(R.id.text_pull_bedno);
        text_pull_markno =findViewById(R.id.text_pull_markno);
        text_pullhead_size1=findViewById(R.id.text_pullhead_size1);
        text_pullhead_size2=findViewById(R.id.text_pullhead_size2);
        text_pullhead_size3=findViewById(R.id.text_pullhead_size3);
        text_pullhead_size4=findViewById(R.id.text_pullhead_size4);
        text_pullhead_size5=findViewById(R.id.text_pullhead_size5);
        text_pullhead_size6=findViewById(R.id.text_pullhead_size6);
        text_pullhead_size7=findViewById(R.id.text_pullhead_size7);
        text_pullhead_size8=findViewById(R.id.text_pullhead_size8);
        text_pullhead_size9=findViewById(R.id.text_pullhead_size9);
        text_pullhead_size10=findViewById(R.id.text_pullhead_size10);
        text_pullhead_size11=findViewById(R.id.text_pullhead_size11);
        text_pullhead_size12=findViewById(R.id.text_pullhead_size12);
        edit_pullvalue_paperName=findViewById(R.id.edit_pullvalue_paperName);
        edit_pullvalue_markWidth=findViewById(R.id.edit_pullvalue_markWidth);
        edit_pullvalue_markLen=findViewById(R.id.edit_pullvalue_markLen);
        edit_pullvalue_useRate=findViewById(R.id.edit_pullvalue_useRate);
        edit_pullvalue_markOperator=findViewById(R.id.edit_pullvalue_markOperator);
        text_pullvalue_size1=findViewById(R.id.text_pullvalue_size1);
        text_pullvalue_size2=findViewById(R.id.text_pullvalue_size2);
        text_pullvalue_size3=findViewById(R.id.text_pullvalue_size3);
        text_pullvalue_size4=findViewById(R.id.text_pullvalue_size4);
        text_pullvalue_size5=findViewById(R.id.text_pullvalue_size5);
        text_pullvalue_size6=findViewById(R.id.text_pullvalue_size6);
        text_pullvalue_size7=findViewById(R.id.text_pullvalue_size7);
        text_pullvalue_size8=findViewById(R.id.text_pullvalue_size8);
        text_pullvalue_size9=findViewById(R.id.text_pullvalue_size9);
        text_pullvalue_size10=findViewById(R.id.text_pullvalue_size10);
        text_pullvalue_size11=findViewById(R.id.text_pullvalue_size11);
        text_pullvalue_size12=findViewById(R.id.text_pullvalue_size12);
        text_pullvalue_total=findViewById(R.id.text_pullvalue_total);
    }


    //获取数据;
    private void ReGetData(String paramCutMaID,String paramMarkDeID,String paramOperType){
        //置值
        String SqlComm="Exec KeyPoint_CutGetData @ProduceCutMaID=\'"+paramCutMaID+"\',@MarkDeID=\'"+paramMarkDeID+"\',@OperatorNo=\'"+curLoginUserNo+"\',@OperType=\'"+paramOperType+"\'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }


    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_RefreshData:
                    btn_Refresh.performClick();

                    break;
                case MSG_MAIN:
                    fillText();
                    break;
                case MSG_PULLLIST:
                    //通过适配器显示;
                    PullListAdapter pullListAdapter=new PullListAdapter(getApplicationContext());
                    pullList.setAdapter(pullListAdapter);
                    showClothFootTotal();
                    curPullListPosition=-1;
                    break;
                case MSG_COLORLIST:
                    //通过适配器显示;
                    ColorListAdapter colorListAdapter=new ColorListAdapter(getApplicationContext());
                    colorList.setAdapter(colorListAdapter);
                    break;
                case MSG_PROCRESULT:
                    String resultMsg = null;
                    try {
                        resultMsg = procRstJSON.optJSONObject(0).getString("PROCRESULT");
                        //提示提交完成，需确认;
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(PullActivity.this)
                                .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        break;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                default:
                    break;
            }
        }
    };

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType")==true) {
                            //System.out.println(jsonArray);
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").toUpperCase().equals("MAIN")==true)
                            {
                                //往界面转数据;
                                titleJson=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_MAIN;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);

                            }
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").toUpperCase().equals("COLORLIST")==true)
                            {
                                colorJson =jsonArray;
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_COLORLIST;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);

                            }
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").toUpperCase().equals("PULLLIST")==true)
                            {
                                pullJson =jsonArray;
                                //保存到数据库中
                                mainDB.execSQL("Delete from PullCloth");
                                for (int i=0;i<pullJson.length();i++) {
                                    mainDB.execSQL("INSERT INTO PullCloth(LevelNo,ProduceCutDeID,ProduceDetailID,ProduceCutMaID,ColorNo,Color,Pertain,BowlNo,IdentLen,LevelNum,PrepNum,RollNum,OwenLen) " +
                                                    "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                            new Object[]{pullJson.optJSONObject(i).getString("LevelNo"), pullJson.optJSONObject(i).getString("ProduceCutDeID")
                                                    , pullJson.optJSONObject(i).getString("ProduceDetailID"), pullJson.optJSONObject(i).getString("ProduceCutMaID")
                                                    , pullJson.optJSONObject(i).getString("ColorNo"), pullJson.optJSONObject(i).getString("Color")
                                                    , pullJson.optJSONObject(i).getString("Pertain"), pullJson.optJSONObject(i).getString("BowlNo")
                                                    , pullJson.optJSONObject(i).get("IdentLen"), pullJson.optJSONObject(i).get("LevelNum")
                                                    , pullJson.optJSONObject(i).get("PrepNum"), pullJson.optJSONObject(i).get("RollNum"), pullJson.optJSONObject(i).get("OwenLen")

                                            });
                                }
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_PULLLIST;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);

                            }
                        }
                        if (jsonArray.getJSONObject(0).has("PROCRESULT")==true) {
                            procRstJSON=jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_PROCRESULT;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);

                        }


                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }

    //填充界面
    private void fillText() {
        if (titleJson!=null) {
            if (titleJson.length()>0){
                JSONObject tmp=titleJson.optJSONObject(0);
                if (tmp!=null) {
                    try {
                        text_pull_department.setText(TransValue(tmp.getString("Department")));
                        text_pull_department.setText(TransValue(tmp.getString("Department")));
                        if (tmp.has("ProduceMasterID")==true) ProduceMasterID=tmp.getString("ProduceMasterID");
                        if (tmp.has("ProduceCutMaID")==true) ProduceCutMaID=tmp.getString("ProduceCutMaID");
                        if (tmp.has("Department")==true) text_pull_department.setText(TransValue(tmp.getString("Department")));
                        if (tmp.has("Operator")==true) text_pull_operator.setText(TransValue(tmp.getString("Operator")));
                        if (tmp.has("FormNo")==true) text_pull_formno.setText(TransValue(tmp.getString("FormNo")));
                        if (tmp.has("FormDate")==true) text_pull_formdate.setText(TransValue(tmp.getString("FormDate")));
                        if (tmp.has("OrderNo")==true) text_pull_orderno.setText(TransValue(tmp.getString("OrderNo")));
                        if (tmp.has("StyleNo")==true) text_pull_styleno.setText(TransValue(tmp.getString("StyleNo")));
                        if (tmp.has("BedNo")==true) text_pull_bedno.setText(TransValue(tmp.getString("BedNo")));
                        if (tmp.has("MarkNo")==true) text_pull_markno.setText(TransValue(tmp.getString("MarkNo")));
                        if (tmp.has("Size1")==true) text_pullhead_size1.setText(TransValue(tmp.getString("Size1")));
                        if (tmp.has("Size2")==true) text_pullhead_size2.setText(TransValue(tmp.getString("Size2")));
                        if (tmp.has("Size3")==true) text_pullhead_size3.setText(TransValue(tmp.getString("Size3")));
                        if (tmp.has("Size4")==true) text_pullhead_size4.setText(TransValue(tmp.getString("Size4")));
                        if (tmp.has("Size5")==true) text_pullhead_size5.setText(TransValue(tmp.getString("Size5")));
                        if (tmp.has("Size6")==true) text_pullhead_size6.setText(TransValue(tmp.getString("Size6")));
                        if (tmp.has("Size7")==true) text_pullhead_size7.setText(TransValue(tmp.getString("Size7")));
                        if (tmp.has("Size8")==true) text_pullhead_size8.setText(TransValue(tmp.getString("Size8")));
                        if (tmp.has("Size9")==true) text_pullhead_size9.setText(TransValue(tmp.getString("Size9")));
                        if (tmp.has("Size10")==true) text_pullhead_size10.setText(TransValue(tmp.getString("Size10")));
                        if (tmp.has("Size11")==true) text_pullhead_size11.setText(TransValue(tmp.getString("Size11")));
                        if (tmp.has("Size12")==true) text_pullhead_size12.setText(TransValue(tmp.getString("Size12")));
                        if (tmp.has("PaperName")==true) edit_pullvalue_paperName.setText(TransValue(tmp.getString("PaperName")));
                        if (tmp.has("MarkWidth")==true) edit_pullvalue_markWidth.setText(TransValue(tmp.getString("MarkWidth")));
                        if (tmp.has("MarkLen")==true) edit_pullvalue_markLen.setText(TransValue(tmp.getString("MarkLen")));
                        if (tmp.has("UseRate")==true) edit_pullvalue_useRate.setText(TransValue(tmp.getString("UseRate")));
                        if (tmp.has("MarkOperator")==true) edit_pullvalue_markOperator.setText(TransValue(tmp.getString("MarkOperator")));
                        if (tmp.has("iSize1")==true) text_pullvalue_size1.setText(TransValue(tmp.getString("iSize1")));
                        if (tmp.has("iSize2")==true) text_pullvalue_size2.setText(TransValue(tmp.getString("iSize2")));
                        if (tmp.has("iSize3")==true) text_pullvalue_size3.setText(TransValue(tmp.getString("iSize3")));
                        if (tmp.has("iSize4")==true) text_pullvalue_size4.setText(TransValue(tmp.getString("iSize4")));
                        if (tmp.has("iSize5")==true) text_pullvalue_size5.setText(TransValue(tmp.getString("iSize5")));
                        if (tmp.has("iSize6")==true) text_pullvalue_size6.setText(TransValue(tmp.getString("iSize6")));
                        if (tmp.has("iSize7")==true) text_pullvalue_size7.setText(TransValue(tmp.getString("iSize7")));
                        if (tmp.has("iSize8")==true) text_pullvalue_size8.setText(TransValue(tmp.getString("iSize8")));
                        if (tmp.has("iSize9")==true) text_pullvalue_size9.setText(TransValue(tmp.getString("iSize9")));
                        if (tmp.has("iSize10")==true) text_pullvalue_size10.setText(TransValue(tmp.getString("iSize10")));
                        if (tmp.has("iSize11")==true) text_pullvalue_size11.setText(TransValue(tmp.getString("iSize11")));
                        if (tmp.has("iSize12")==true) text_pullvalue_size12.setText(TransValue(tmp.getString("iSize12")));
                        if (tmp.has("Total")==true) text_pullvalue_total.setText(TransValue(tmp.getString("Total")));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }


    public  String TransValue(String params)
    {
        if (params.toUpperCase().equals("NULL")||params.equals("0")||params.equals("0.0"))
            return "";
        else return params;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_Refresh:
                ReGetData(ProduceCutMaID,MarkDeID,"MAIN");
                ReGetData(ProduceCutMaID,MarkDeID,"COLORLIST");
                ReGetData(ProduceCutMaID,MarkDeID,"PULLLIST");
                break;
            case R.id.btn_Close:
                finish();
                break;
            case R.id.btn_Edit:
                if (MakeState.equals("READY")==true){
                    curToast.setText("已生成床次不能被编辑！");
                    curToast.show();
                    return;
                }
                if ((curPullListPosition>-1)&&(curPullListPosition<pullJson.length())) showPullLevel(curPullListPosition,false);
                else {
                    curToast.setText("请选择需要的编辑的行!");
                    curToast.show();
                }
                break;
            case R.id.btn_Delete:
                if (MakeState.equals("READY")==true){
                    curToast.setText("已生成床次不能被编辑！");
                    curToast.show();
                    return;
                }
                if ((curPullListPosition>-1)&&(curPullListPosition<pullJson.length()))
                {
                    try {
                        curProduceCutDeID=pullJson.optJSONObject(curPullListPosition).getString("ProduceCutDeID");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle("系统提示").setMessage("你确定要删除选中的拉布信息吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    pullJson.remove(curPullListPosition);
                                    mainDB.execSQL("Delete from PullCloth where ProduceCutDeID=?",new String[]{curProduceCutDeID});
                                    //更新显示;
                                    ((BaseAdapter)pullList.getAdapter()).notifyDataSetChanged();
                                    showClothFootTotal();
                                }
                            }).setNegativeButton("取消",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框

                }else {
                    curToast.setText("请选择需要的删除的行!");
                    curToast.show();
                }
                break;
            case R.id.btn_Submit:
                if (MakeState.equals("READY")==true){
                    curToast.setText("已生成床次不能被编辑！");
                    curToast.show();
                    return;
                }
                if ((pullJson==null)||(pullJson.length()==0)) {
                    curToast.setText("数据为空，不能提交!");
                    curToast.show();
                    return;
                }
                SavePullDetail();
                break;
            default:
                break;
        }

    }
    //提交所选择的工序至服务器,然后刷新工序列表;
    private void SavePullDetail() {
        if (pullJson==null) return;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String ScenePullMaID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into ScenePullDe(ScenePullDeID,ScenePullMaID,ProduceCutDeID,ProduceDetailID,LevelNo,BowlNo,IdentLen,LevelNum,PrepNum,RollNum,ShortLen,OwenLen)values(newid(),?,?,?,?,?,?,?,?,?,?,?)");
                    //增加明细表
                    for (int i = 0; i < pullJson.length(); i++) {
                        if (pullJson.getJSONObject(i).has("RealMeasure") == true) {
                            if (pullJson.getJSONObject(i).getString("RealMeasure").length() > 0) {
                                pstmt.setString(1, ScenePullMaID);
                                pstmt.setString(2, pullJson.getJSONObject(i).getString("ProduceCutDeID"));
                                pstmt.setString(3, pullJson.getJSONObject(i).getString("ProduceDetailID"));
                                pstmt.setString(4, pullJson.getJSONObject(i).getString("LevelNo"));
                                pstmt.setString(5, pullJson.getJSONObject(i).getString("BowlNo"));
                                pstmt.setString(6, pullJson.getJSONObject(i).getString("IdentLen"));
                                pstmt.setString(7, pullJson.getJSONObject(i).getString("LevelNum"));
                                pstmt.setString(8, pullJson.getJSONObject(i).getString("PrepNum"));
                                pstmt.setString(9, pullJson.getJSONObject(i).getString("RollNum"));
                                pstmt.setString(10, pullJson.getJSONObject(i).getString("ShortLen"));
                                pstmt.setString(11, pullJson.getJSONObject(i).getString("OwenLen"));
                                pstmt.executeUpdate();
                            }
                        }
                    }
                    pstmt.close();
                    //增加主表;
                    pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into ScenePullMa(ScenePullMaID,ProduceMasterID,ProduceCutMaID,MarkDeID,Department,Operator,BedNo,UserNo,CreateTime) values(?,?,?,?,?,?,?,?,getdate())");
                    pstmt.setString(1, ScenePullMaID);
                    pstmt.setString(2, ProduceMasterID);
                    pstmt.setString(3, ProduceCutMaID);
                    pstmt.setString(4, MarkDeID);
                    pstmt.setString(5, text_pull_department.getText().toString());
                    pstmt.setString(6, text_pull_operator.getText().toString());
                    pstmt.setString(7, text_pull_bedno.getText().toString());
                    pstmt.setString(8, curLoginUserNo);
                    pstmt.executeUpdate();
                    pstmt.close();
                    //调用存储过程;
                    SqlComm = " Exec ScenePAD_TransScenePull @ScenePullMaID='" + ScenePullMaID + "'";
                    ReadSQLData(SqlComm);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.e(TAG,"onItemClick");
        if (parent==colorList)
        {
            if (MakeState.equals("READY")==true){
                curToast.setText("已生成床次不能被编辑！");
                curToast.show();
                return;
            }
            try {
                Cursor cur = mainDB.rawQuery("Select ifnull(Max(LevelNo),0) LevelNo from PullCloth", null);
                if (cur.getCount() > 0) {
                    cur.moveToFirst();
                    curLevelNo=String.valueOf(cur.getInt(cur.getColumnIndex("LevelNo"))+1);
                } else curLevelNo="1";
                Log.e(TAG,curLevelNo);
                curProduceCutDeID= UUID.randomUUID().toString();
                curProduceDetailID=colorJson.optJSONObject(position).getString("ProduceDetailID");
                curColor=colorJson.optJSONObject(position).getString("Color");
                curColorNo=colorJson.optJSONObject(position).getString("ColorNo");
                curPertain=colorJson.optJSONObject(position).getString("Pertain");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //弹出输入框
            showPullLevel(position,true);
        }
        if (parent==pullList)
        {
            curPullListPosition=position;
        }

    }

    private void showPullLevel(final int position,final boolean append){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View pull_input=inflater.inflate(R.layout.pull_input, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        //临时加载
        try {
            final EditText text_BowlNo=pull_input.findViewById(R.id.text_BowlNo);
            text_BowlNo.setInputType(InputType.TYPE_CLASS_TEXT);
            if (append==false) text_BowlNo.setText(pullJson.getJSONObject(position).getString("BowlNo"));
            final EditText text_IdentLen=pull_input.findViewById(R.id.text_IdentLen);
            text_IdentLen.setInputType(0x2002);
            if (append==false) text_IdentLen.setText(TransValue(pullJson.getJSONObject(position).getString("IdentLen")));
            final EditText text_LevelNum=pull_input.findViewById(R.id.text_LevelNum);
            text_LevelNum.setInputType(0x2002);
            if (append==false) text_LevelNum.setText(TransValue(pullJson.getJSONObject(position).getString("LevelNum")));
            final EditText text_PrepNum=pull_input.findViewById(R.id.text_PrepNum);
            text_PrepNum.setInputType(0x2002);
            if (append==false) text_PrepNum.setText(TransValue(pullJson.getJSONObject(position).getString("PrepNum")));
            final EditText text_RollNum=pull_input.findViewById(R.id.text_RollNum);
            text_RollNum.setInputType(0x2002);
            if (append==false) text_RollNum.setText(TransValue(pullJson.getJSONObject(position).getString("RollNum")));
            final EditText text_OwenLen=pull_input.findViewById(R.id.text_OwenLen);
            text_OwenLen.setInputType(0x2002);
            if (append==false) text_OwenLen.setText(TransValue(pullJson.getJSONObject(position).getString("OwenLen")));
            //创建对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setView(pull_input).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                if (text_LevelNum.getText().length()==0){
                                    curToast.setText("请输入件数!");
                                    curToast.show();
                                    return;
                                }
                                if (append==false) {
                                    if (text_BowlNo.getText().length() > 0)
                                        pullJson.getJSONObject(position).put("BowlNo", text_BowlNo.getText());
                                    else pullJson.getJSONObject(position).put("BowlNo", "");
                                    if (text_IdentLen.getText().length() > 0)
                                        pullJson.getJSONObject(position).put("IdentLen", text_IdentLen.getText());
                                    else pullJson.getJSONObject(position).put("IdentLen", "0");
                                    if (text_LevelNum.getText().length() > 0)
                                        pullJson.getJSONObject(position).put("LevelNum", text_LevelNum.getText());
                                    else pullJson.getJSONObject(position).put("LevelNum", "0");
                                    if (text_PrepNum.getText().length() > 0)
                                        pullJson.getJSONObject(position).put("PrepNum", text_PrepNum.getText());
                                    else pullJson.getJSONObject(position).put("PrepNum", "0");
                                    if (text_RollNum.getText().length() > 0)
                                        pullJson.getJSONObject(position).put("RollNum", text_RollNum.getText());
                                    else pullJson.getJSONObject(position).put("RollNum", "0");
                                    if (text_OwenLen.getText().length() > 0)
                                        pullJson.getJSONObject(position).put("OwenLen", text_OwenLen.getText());
                                    else pullJson.getJSONObject(position).put("OwenLen", "0");
                                    mainDB.execSQL("UPDATE  PullCloth set BowlNo=?,IdentLen=?,LevelNum=?,PrepNum=?,RollNum=?,OwenLen=? where ProduceCutDeID=? ",
                                            new Object[]{pullJson.optJSONObject(position).getString("BowlNo")
                                                    , pullJson.optJSONObject(position).getString("IdentLen"), pullJson.optJSONObject(position).getString("LevelNum")
                                                    , pullJson.optJSONObject(position).getString("PrepNum"), pullJson.optJSONObject(position).getString("RollNum")
                                                    , pullJson.optJSONObject(position).getString("OwenLen")
                                                    , pullJson.optJSONObject(position).getString("ProduceCutDeID")});
                                    //更新到表格列表;
                                    ((BaseAdapter)pullList.getAdapter()).notifyDataSetChanged();
                                } else
                                {
                                    JSONObject tmpJson=new JSONObject();
                                    tmpJson.put("LevelNo",curLevelNo);
                                    tmpJson.put("ProduceCutDeID", curProduceCutDeID);
                                    tmpJson.put("ProduceDetailID",curProduceDetailID);
                                    tmpJson.put("ProduceCutMaID", ProduceCutMaID);
                                    tmpJson.put("Color", curColor);
                                    tmpJson.put("ColorNo", curColorNo);
                                    tmpJson.put("Pertain", curPertain);
                                    if (text_BowlNo.getText().length() > 0) tmpJson.put("BowlNo", text_BowlNo.getText());else tmpJson.put("BowlNo", "");
                                    if (text_IdentLen.getText().length() > 0) tmpJson.put("IdentLen", text_IdentLen.getText());else tmpJson.put("IdentLen", "0");
                                    if (text_LevelNum.getText().length() > 0) tmpJson.put("LevelNum", text_LevelNum.getText());else tmpJson.put("LevelNum", "0");
                                    if (text_PrepNum.getText().length() > 0) tmpJson.put("PrepNum", text_PrepNum.getText());else tmpJson.put("PrepNum", "0");
                                    if (text_RollNum.getText().length() > 0) tmpJson.put("RollNum", text_RollNum.getText());else tmpJson.put("RollNum", "0");
                                    if (text_OwenLen.getText().length() > 0) tmpJson.put("OwenLen", text_OwenLen.getText());else tmpJson.put("OwenLen", "0");
                                    pullJson.put(tmpJson);
                                    //保存到数据库里
                                    mainDB.execSQL("INSERT INTO PullCloth(LevelNo,ProduceCutDeID,ProduceDetailID,ProduceCutMaID,ColorNo,Color,Pertain,BowlNo,IdentLen,LevelNum,PrepNum,RollNum,ShortLen,OwenLen) " +
                                                    "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                            new Object[]{tmpJson.getString("LevelNo"), tmpJson.getString("ProduceCutDeID")
                                                    , tmpJson.getString("ProduceDetailID"), tmpJson.getString("ProduceCutMaID")
                                                    , tmpJson.getString("ColorNo"), tmpJson.getString("Color")
                                                    , tmpJson.getString("Pertain"), tmpJson.getString("BowlNo")
                                                    , tmpJson.get("IdentLen"), tmpJson.get("LevelNum")
                                                    , tmpJson.get("PrepNum"), tmpJson.get("RollNum"),"0", tmpJson.get("OwenLen")});
                                    //通过适配器显示;
                                    System.out.println(pullJson);
                                    PullListAdapter pullListAdapter=new PullListAdapter(getApplicationContext());
                                    pullList.setAdapter(pullListAdapter);
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            //显示汇总页脚
                            showClothFootTotal();
                            hideIM(pull_input);
                        }
                    }
            ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    hideIM(pull_input);
                    Log.v("tag","取消");
                }
            }).setTitle("系统输入框");
            builder.show();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //显示汇总页脚;
    private void showClothFootTotal() {
        Cursor cur = mainDB.rawQuery("Select sum(IdentLen) IdentLen,sum(LevelNum) LevelNum,sum(PrepNum) PrepNum,sum(RollNum) RollNum,sum(ShortLen) ShortLen,sum(OwenLen) OwenLen from PullCloth", null);
        if (cur.getCount() > 0) {
            cur.moveToFirst();
            TextView txt_item_IdentLen = findViewById(R.id.txt_foot_IdentLen);
            txt_item_IdentLen.setText(cur.getString(cur.getColumnIndex("IdentLen")));
            TextView txt_item_LevelNum=findViewById(R.id.txt_foot_LevelNum);
            txt_item_LevelNum.setText(cur.getString(cur.getColumnIndex("LevelNum")));
            TextView txt_item_PrepNum=findViewById(R.id.txt_foot_PrepNum);
            txt_item_PrepNum.setText(cur.getString(cur.getColumnIndex("PrepNum")));
            TextView txt_item_RollNum=findViewById(R.id.txt_foot_RollNum);
            txt_item_RollNum.setText(cur.getString(cur.getColumnIndex("RollNum")));
            TextView txt_item_OwenLen=findViewById(R.id.txt_foot_OwenLen);
            txt_item_OwenLen.setText(cur.getString(cur.getColumnIndex("OwenLen")));
        }
    }




    @Override
    public void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("PullActivity----onStart");
    }

    @Override
    public void onPause() {
        super.onPause();
        stopMusic();
        System.out.println("PullActivity----onPause");
    }

    /**
     * 创建网络mp3
     * @return
     */
    public MediaPlayer createNetMp3(){
        String url=curServiceDir+"/warn.mp3";
        System.out.println("音乐文件地址："+url);
        MediaPlayer mp=new MediaPlayer();
        try {
            mp.setDataSource(url);
        } catch (IllegalArgumentException e) {
            return null;
        } catch (IllegalStateException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
        return mp;
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

        return false;
    }

    //订单表格适配器;
    public final class ColorListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ColorListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return colorJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return colorJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.pull_colorlist_item, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (colorJson.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = colorJson.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv =  convertView.findViewById(R.id.txt_item_Color);// 显示文字
                if (colorJson.optJSONObject(position).has("Color")==true)
                    tv.setText(colorJson.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_ColorNo);// 显示文字
                if (colorJson.optJSONObject(position).has("ColorNo")==true)
                    tv.setText(colorJson.optJSONObject(position).get("ColorNo").toString());
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_Pertain);// 显示文字
                if (colorJson.optJSONObject(position).has("Pertain")==true)
                    tv.setText(colorJson.optJSONObject(position).get("Pertain").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_LevelNum);// 显示文字
                if (colorJson.optJSONObject(position).has("LevelNum")==true)
                    tv.setText(colorJson.optJSONObject(position).get("LevelNum").toString());

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","ColorListAdapter_position:"+position);
            return convertView;
        }
    }


    //订单表格适配器;
    public final class PullListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public PullListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return pullJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return pullJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.pull_right_clothhead, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg","getView()a----------------------------------------------------->"+position);
                if (pullJson.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = pullJson.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv =  convertView.findViewById(R.id.txt_item_Color);// 显示文字
                if (pullJson.optJSONObject(position).has("Color")==true)
                    tv.setText(pullJson.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_ColorNo);// 显示文字
                if (pullJson.optJSONObject(position).has("ColorNo")==true)
                    tv.setText(pullJson.optJSONObject(position).get("ColorNo").toString());
                tv.setTextColor(color);
                tv =  convertView.findViewById(R.id.txt_item_Pertain);// 显示文字
                if (pullJson.optJSONObject(position).has("Pertain")==true)
                    tv.setText(pullJson.optJSONObject(position).get("Pertain").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_BowlNo);// 显示文字
                if (pullJson.optJSONObject(position).has("BowlNo")==true)
                    tv.setText(pullJson.optJSONObject(position).get("BowlNo").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_IdentLen);// 显示文字
                if (pullJson.optJSONObject(position).has("IdentLen")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("IdentLen").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_LevelNum);// 显示文字
                if (pullJson.optJSONObject(position).has("LevelNum")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("LevelNum").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_PrepNum);// 显示文字
                if (pullJson.optJSONObject(position).has("PrepNum")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("PrepNum").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_RollNum);// 显示文字
                if (pullJson.optJSONObject(position).has("RollNum")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("RollNum").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.txt_item_OwenLen);// 显示文字
                if (pullJson.optJSONObject(position).has("OwenLen")==true)
                    tv.setText(TransValue(pullJson.optJSONObject(position).get("OwenLen").toString()));
                tv.setTextColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","PullListAdapter_position:"+position);
            return convertView;
        }
    }

    //插放音乐;
    private void playMusic(){
        try {
            if(mediaPlayer==null) {
                mediaPlayer = createNetMp3();
                mediaPlayer.setLooping(false);
                //在播放音频资源之前，必须调用Prepare方法完成些准备工作
                mediaPlayer.prepare();
            }
            if(mediaPlayer!=null) {
                if (mediaPlayer.isPlaying()==false) mediaPlayer.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //停止播放音乐
    private  void  stopMusic(){
        if(mediaPlayer!=null){
            mediaPlayer.stop();//停止播放
            mediaPlayer.release();//释放资源
            mediaPlayer=null;
        }
    }

}
